package git.soulbgm;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * TCP服务端处理程序
 *
 * @author SoulBGM
 * @date 2022/04/20 00:19
 */
@ChannelHandler.Sharable
public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public final static List<Channel> CLIENT_LIST = new CopyOnWriteArrayList<>();

    /**
     * 当客户端连接时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        CLIENT_LIST.add(ctx.channel());
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        CLIENT_LIST.remove(ctx.channel());
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        // 接收时间
        long rcvTime = System.currentTimeMillis();
        // 数据
        byte[] data = ByteBufUtil.getBytes(msg);

        byte[] ntpPacket = NtpdateUtil.getNtpResponsePacket(rcvTime, data);
        ChannelUtil.tcpSendMsg(ctx.channel(), ntpPacket);
    }

}
